//
//  UIImage+Extension.m
//  YBInsurance
//
//  Created by S2 on 15/6/10.
//  Copyright (c) 2015年 YB. All rights reserved.
//

#import "UIImage+Extension.h"

@implementation UIImage (Extension)

+ (NSData *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    
    CGFloat compression = 0.8;
    NSData *uploadImageData = UIImageJPEGRepresentation(image, compression);
    
    CGFloat imageDataLength = uploadImageData.length;
    CGSize size = image.size;
    CGFloat imageWidth = size.width;
    CGFloat imageHeight = size.height;
    
    UIImage *imageCope;
    
    if ((imageDataLength > maxLength && maxLength > 0) || (imageWidth > 2500 || imageHeight > 2500)) {
            
        /* 宽高的比例 **/
        CGFloat ratioOfWH = imageWidth / imageHeight;
        /* 压缩率 **/
        CGFloat compressionRatio = maxLength / imageDataLength;
        /* 宽度或者高度的压缩率 **/
        CGFloat widthOrHeightCompressionRatio = sqrt(compressionRatio);
        
        CGFloat dWidth   = imageWidth *widthOrHeightCompressionRatio;
        CGFloat dHeight  = imageHeight*widthOrHeightCompressionRatio;
//        if (ratioOfWH > 1) { /* 宽 > 高,说明宽度的压缩相对来说更大些 **/
//            dHeight = dWidth/ratioOfWH;
//        }else {
//            dWidth  = dHeight*ratioOfWH;
//        }
        
        imageCope = [UIImage drawWithWithImage:image width:dWidth height:dHeight];
        uploadImageData = UIImageJPEGRepresentation(imageCope, 0.7);
        
        NSLog(@"当前的图片已经压缩成 %fKB", uploadImageData.length / 1024.0);
        //微调
        NSInteger compressCount = 0;
//         控制在 1M 以内*
        while (fabs(uploadImageData.length - maxLength) > 1024) {
            /* 再次压缩的比例**/
            CGFloat nextCompressionRatio = 0.8;

            if (uploadImageData.length > maxLength) {
                
                dWidth = dWidth * nextCompressionRatio;
                dHeight = dHeight * nextCompressionRatio;
            } else {
                
                dWidth = dWidth / nextCompressionRatio;
                dHeight= dHeight / nextCompressionRatio;
            }

            imageCope = [UIImage drawWithWithImage:imageCope width:dWidth height:dHeight];
            uploadImageData = UIImageJPEGRepresentation(imageCope, 0.8);

            /*防止进入死循环**/
            compressCount ++;
            if (compressCount == 10) {
                break;
            }
        }
        return uploadImageData;
//        imageCope = [[UIImage alloc] initWithData:uploadImageData];
    } else {
        
        return uploadImageData;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
//    if (data.length < maxLength) return data;
//
//    CGFloat max = 1;
//    CGFloat min = 0;
//    for (int i = 0; i < 6; ++i) {
//        compression = (max + min) / 2;
//        data = UIImageJPEGRepresentation(image, compression);
//        if (data.length < maxLength * 0.9) {
//            min = compression;
//        } else if (data.length > maxLength) {
//            max = compression;
//        } else {
//            break;
//        }
//    }
//    UIImage *resultImage = [UIImage imageWithData:data];
//    if (data.length < maxLength) return data;
//
//    // Compress by size
//    NSUInteger lastDataLength = 0;
//    while (data.length > maxLength && data.length != lastDataLength) {
//        lastDataLength = data.length;
//        CGFloat ratio = (CGFloat)maxLength / data.length;
//        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
//                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
////        UIGraphicsBeginImageContext(size);
//        UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
//        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
//        resultImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//        data = UIImageJPEGRepresentation(resultImage, compression);
//    }
//
//    return data;
}

+ (UIImage *)drawWithWithImage:(UIImage *)imageCope width:(CGFloat)dWidth height:(CGFloat)dHeight{
    
    UIGraphicsBeginImageContext(CGSizeMake(dWidth, dHeight));
    [imageCope drawInRect:CGRectMake(0, 0, dWidth, dHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (UIImage *)clipImage:(UIImage *)image byWidth:(CGFloat)clipWidth height:(CGFloat)clipHeight {
    
    CGFloat oldWidth = image.size.width;
    CGFloat oldHeight = image.size.height;
    
    if (oldWidth < clipWidth) {
        
        return image;
    }
    
    CGFloat scale = oldWidth / oldHeight;
    CGFloat newHeight = clipWidth / scale;
    
    CGRect scaleFrame = CGRectMake(0, 0, clipWidth, newHeight);
    
//    UIGraphicsBeginImageContext(CGSizeMake(clipWidth, newHeight));
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(clipWidth, newHeight), NO, [[UIScreen mainScreen] scale]);
    [image drawInRect:scaleFrame];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    if (newHeight > clipWidth) {
        
        newHeight = clipHeight;
    } else {
        
        return reSizeImage;
    }
    
    CGRect clipFrame = CGRectMake(0, 0, clipWidth, newHeight);
    
    CGImageRef imgRef = CGImageCreateWithImageInRect(reSizeImage.CGImage, clipFrame);
    
    UIGraphicsBeginImageContextWithOptions(clipFrame.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, clipFrame.size.height);
    CGContextScaleCTM(context, 1, -1);
    CGContextDrawImage(context, CGRectMake(0, 0, clipFrame.size.width, clipFrame.size.height), imgRef);
    
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRelease(imgRef);
    UIGraphicsEndImageContext();
    return newImg;
}

- (UIImage *)scaleWithWidth:(CGFloat)width compressionQuality:(CGFloat)quality {
    
    if (self.size.width < width || width <= 0) {
        
        return self;
    }
    
    CGFloat scale = self.size.width / self.size.height;
    CGSize newSize = CGSizeMake(width, width / scale);
    
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 1);

    [self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if (quality == 1) {
        
        return reSizeImage;
    }
    NSData *imageData = UIImageJPEGRepresentation(reSizeImage, quality);
    UIImage *newImage = [UIImage imageWithData: imageData];
    return newImage;
}


+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize {
    
    UIImage *newImage = nil;
    CGSize imageSize = image.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = asize.width;
    CGFloat targetHeight = asize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if (CGSizeEqualToSize(imageSize, asize) == NO) {
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor) {
           
            scaleFactor = widthFactor;
        } else {
            
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if (widthFactor > heightFactor) {
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else if(widthFactor < heightFactor) {
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
//    UIGraphicsBeginImageContext(asize);
    UIGraphicsBeginImageContextWithOptions(asize, NO, [[UIScreen mainScreen] scale]);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [image drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)imageWithHexColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
//    UIGraphicsBeginImageContext(rect.size);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    //首先根据image的size的长宽比和newSize进行设置新图片的大小（为了达到等比例缩放不变形的目的）
    CGFloat wTmp;
    CGFloat hTmp;
    CGSize imgSize = image.size;
    if (imgSize.width > imgSize.height) {
        wTmp=newSize.width;
        hTmp = imgSize.height * wTmp / imgSize.width;
    } else {
        hTmp=newSize.height;
        wTmp = imgSize.width * hTmp / imgSize.height;
    }
    
    // Create a graphics image context
    UIGraphicsBeginImageContext(CGSizeMake(wTmp, hTmp));
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,wTmp,hTmp)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}



@end
